package com.sams.controller;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.CountrySub;
import com.sams.entity.School;
import com.sams.entity.Student;
import com.sams.entity.User;
import com.sams.service.BaseInfoService;
import com.sams.service.CountrySubService;
import com.sams.service.DataTotalService;
import com.sams.service.SchoolService;
import com.sams.util.POIUtil;
import com.sams.util.watermark;

/**
 * 国家资助模块 Controller
 * 
 * @author 您好！小马！
 */
@RequestMapping("/countrysub")
@Controller
public class CountrySubController {

	@Autowired
	private CountrySubService service;
	@Autowired
	private BaseInfoService baseInfoService;
	@Autowired
	private DataTotalService dataTotalService;
	@Autowired
	private SchoolService schoolService;
	
	/* @Value("${imagePath}") 
	 * */
	//@Value("E:/images")
	@Value("#{prop.imagePath}")
	private String uploadPath;
 

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	// 页面跳转
	@RequestMapping("/list")
	public String listCountrySub(Integer currentPage, Model model, String name, 
			String idcard, Integer schid,String project,Integer zid,String x,
			HttpServletRequest request,HttpSession session) {
 		if (currentPage == null) {
			currentPage = 1;
		}
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		//分页查询时，条件的来源 
		if(x!=null) {// 说明是分页信息
			//从session中获取条件
			name=(String)session.getAttribute("name");
			idcard=(String)session.getAttribute("idcard");
			schid=(Integer)session.getAttribute("schid");
			zid=(Integer)session.getAttribute("zid");
			project=(String)session.getAttribute("project");
		}
		//查询所有的乡镇
				if(user.getRoleid()==1 ||user.getRoleid()==2) {
					 //查询所有镇id
					model.addAttribute("xzList", baseInfoService.findById(user.getZid()));
				}else { 
					 model.addAttribute("xzList", dataTotalService.selectAllZhen());
				}
		//System.out.println("12");
		PageInfo<CountrySub> pageInfo = service.listStu(currentPage, name, idcard, schid, project,user,zid);
		model.addAttribute("pageInfo", pageInfo);
		session.setAttribute("name", name);
		session.setAttribute("idcard", idcard);
		session.setAttribute("schid", schid);
		session.setAttribute("project", project);
		session.setAttribute("zid", zid);
		//如果已选zid ，则需要回显它对应的学校，方便继续选择其他学校
		if(zid!=null && !zid.toString().equals("0")) {
			model.addAttribute("schoolListByZid",schoolService.selectSchoolByZid(zid));
		}
		return "countorysub";
	}

	// 主页面跳转
	@RequestMapping("/addBy")
	public String addBy(HttpServletRequest request, Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		return "countorysub_add";
	}

	// 主页面添加
	@RequestMapping("/addByCountrySub")
	public String addByCountrySub(CountrySub sub, HttpServletRequest request, Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		sub.setUid(user.getId());
		sub.setStatus(1);
		try {
			//业务验证
			String state = service.selectIdCard(sub.getIdcard(), sub.getProject(),sub.getSchid(),null);
			
			if (state == "negativeErr") {//负面清单中存在,不能添加
				throw new Exception("负面清单中存在,不能添加!");
			} else if (state == "countrySubErr") {//国家资助同一受助项目重复,不能添加
				throw new Exception("国家资助同一受助项目重复,不能添加!");
			} else if (state == "studentYes") {//在校学生存在,可以添加
			} else if (state == "departListYes") {//部门对比存在,可以添加
			} else if (state == "notIn") {//非在校学生或部门对比学生,不能添加
				throw new Exception("非在校学生或部门对比学生,不能添加!");
				//syalert.syopen("alert4");
			}
			
			int count = service.add(sub);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "error";
		}
		return "redirect:list";
	}

	// 主页面修改查询
	@RequestMapping("/updateBySelectCountrySub")
	public String updateBySelectCountrySub(int id, HttpServletRequest request, Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		CountrySub sub = service.findById(id);
		model.addAttribute("Sub", sub);
		return "countorysub_update";
	}
	
	// 主页面修改
	@RequestMapping("/updateByCountrySub")
	public String updateByCountrySub(CountrySub sub, HttpServletRequest request, Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		sub.setUid(user.getId());
		sub.setStatus(1);
		try {
			String state = service.selectIdCard(sub.getIdcard(), sub.getProject(),sub.getSchid(),sub.getId());
			
			if (state == "negativeErr") {//负面清单中存在,不能添加
				throw new Exception("负面清单中存在,不能添加!");
			} else if (state == "countrySubErr") {//国家资助同一受助项目重复,不能添加
				throw new Exception("国家资助同一受助项目重复,不能添加!");
			} else if (state == "studentYes") {//在校学生存在,可以添加
			} else if (state == "departListYes") {//部门对比存在,可以添加
			} else if (state == "notIn") {//非在校学生或部门对比学生,不能添加
				throw new Exception("非在校学生或部门对比学生,不能添加!");
				//syalert.syopen("alert4");
			}
			service.update(sub);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "error";
		}
		return "redirect:list";
	}

	// 主页面删除
	@RequestMapping("/deleteById")
	public String deleteById(Integer id) {
		service.delete(id);
		return "redirect:list";
	}

	// 跳转详情页
	@RequestMapping("/selectById")
	public String selectById(int id,HttpServletRequest request,Model model) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		CountrySub sub = service.findById(id);
		model.addAttribute("Sub", sub);
		return "countorysub_detail";
	}
	
	// 主页面添加图片 (不需要水印) (demo1)
	@RequestMapping("/updateByImg")
	public String updateByImg(@RequestParam("id") Integer id,
			@RequestParam("applyfile") MultipartFile applyfile,
			@RequestParam("apply2file") MultipartFile apply2file, 
			@RequestParam("apply3file") MultipartFile apply3file,
			@RequestParam("idcardfile") MultipartFile idcardfile,
			@RequestParam("idcard2file") MultipartFile idcard2file, 
			@RequestParam("stufile") MultipartFile stufile,
			@RequestParam("addressfile") MultipartFile addressfile,
			@RequestParam("address2file") MultipartFile address2file,
			@RequestParam("bankfile") MultipartFile bankfile, Model model)
			  {
		// 名称改成用户ID+名字applyfile varchar "申请表缩略图
		/*
		 * apply2file 认定表缩略图 apply3file 其他家庭经济情况作证材料缩略图 idcardfile varchar 学生身份证正面缩略图
		 * idcard2file varchar 学生身份证反面缩略图 stufile 学生户口页缩略图 addressfile varchar
		 * 学生家庭户口簿家庭成员页缩略图 address2file varchar 家长或监护人户口页缩略图 bankfile 银行卡或存折缩略图
		 */
		// watermark.markImageByText("老伍and小丰子",
		// "E:\\images\\"+myfile.getOriginalFilename(), "E:\\images\\1.jpg", 45, new
		// Color(205,205,205), "JPG");
		// File file = new File("E:\\images\\"+myfile.getOriginalFilename());
		
		
		File file = new File(uploadPath+File.separator+"countorysub");
		if(!file.exists()) {
			file.mkdirs();//不存在就创建
		}
		//获取新 文件名 
		String filePath = file.getPath();
		System.out.println("上传路径----"+filePath);
		String applyfile_1 = getFileName(applyfile.getOriginalFilename());
		String apply2file_1 = getFileName(apply2file.getOriginalFilename());
		String apply3file_1 = getFileName(apply3file.getOriginalFilename());
		String idcardfile_1 = getFileName(idcardfile.getOriginalFilename());
		String idcard2file_1 = getFileName(idcard2file.getOriginalFilename());
		String stufile_1 = getFileName(stufile.getOriginalFilename());
		String addressfile_1 = getFileName(addressfile.getOriginalFilename());
		String addressfile_2 = getFileName(address2file.getOriginalFilename());
		String bankfile_1 = getFileName(bankfile.getOriginalFilename());
		
 
		try {
			applyfile.transferTo(new File(filePath+ File.separator +applyfile_1));
			apply2file.transferTo(new File(filePath+ File.separator +apply2file_1));
			apply3file.transferTo(new File(filePath+ File.separator +apply3file_1));
			idcardfile.transferTo(new File(filePath+ File.separator +idcardfile_1));
			idcard2file.transferTo(new File(filePath+ File.separator +idcard2file_1));
			stufile.transferTo(new File(filePath+ File.separator +stufile_1));
			addressfile.transferTo(new File(filePath+ File.separator +addressfile_1));
			address2file.transferTo(new File(filePath+ File.separator +addressfile_2));
			bankfile.transferTo(new File(filePath+ File.separator +bankfile_1));
			
			System.out.println("文件上传成功");
			//添加记录 
			CountrySub sub = new CountrySub();
			sub.setId(id);
			sub.setApplyfile("countorysub/"+applyfile_1);
			sub.setApply2file("countorysub/"+apply2file_1);
			sub.setApply3file("countorysub/"+apply3file_1);
			sub.setIdcardfile("countorysub/"+idcardfile_1);
			sub.setIdcard2file("countorysub/"+idcard2file_1);
			sub.setStufile("countorysub/"+stufile_1);
			sub.setAddressfile("countorysub/"+addressfile_1);
			sub.setAddress2file("countorysub/"+addressfile_2);
			sub.setBankfile("countorysub/"+bankfile_1);
			
			boolean flag = service.updateFile(sub);
			System.out.println("================="+flag);
			if(flag) {
				 return "forward:/countrysub/list";
			}else {
				
				model.addAttribute("error", "数据库插入失败，请稍后<br/>");
				return "error";
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
			model.addAttribute("error", "系统异常，请稍后<br/>"+e.getMessage());
			return "error";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error", "文件上传失败，请检查是否存在遗漏或联系管理员<br/>"+e.getMessage());
			return "error";
		}
	
		 
	}
	/**
	 * 根据文件名 创建一个新的文件名
	 * @param fileName
	 * @return
	 */
	public String getFileName(String fileName) {
		  String filePrefix=fileName.substring(0,fileName.lastIndexOf('.'));
		        String fileSuffix=fileName.substring(fileName.lastIndexOf('.'), fileName.length());
		       return filePrefix+(int)(Math.random()*9000+1000)+fileSuffix;
     }
	// 添加页面查询身份证信息
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("/selectByIdCard") public String selectByIdCard(String
	 * idcard, String project) { String state = service.selectIdCard(idcard,
	 * project); System.err.println(state); return state; }
	 */
	
	/***************************************************/
	@RequestMapping("/downTemplate")
	public String downTemplate(HttpServletRequest request, HttpServletResponse response) {
		 // 1: 找到excel文件
        String storePath = request.getSession().getServletContext().getRealPath("/") + "template/countrysub/";
        String fileName = "国家资助批量导入.xlsx";

        File file = new File(storePath + fileName);
        if (!file.exists()) {
            throw new RuntimeException("file do not exist，filepath->>"+(storePath + fileName));
        }
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        // 重置response
        response.reset();
        //设置http头信息的内容
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        int fileLength = (int) file.length();
        response.setContentLength(fileLength);

        try {
            if (fileLength != 0) {
                inputStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                // 创建输出流
                servletOutputStream = response.getOutputStream();
                int readLength;
                // 读取文件内容并输出到response的输出流中
                while ((readLength = inputStream.read(buf)) != -1) {
                    servletOutputStream.write(buf, 0, readLength);
                }
            }
        } catch (IOException e) {
        	e.printStackTrace();
            throw new RuntimeException("download file error");
        } finally {
            try {
                // 关闭ServletOutputStream
                if (servletOutputStream != null) {
                    servletOutputStream.flush();
                    servletOutputStream.close();
                }
                // 关闭InputStream
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
 
	}

	/**
	 * excel批量导入
	 * @return
	 */
	@RequestMapping("/importBetch")
	public String ExcelInport(@RequestParam("file") MultipartFile file,HttpServletRequest request,Model model) {
		// 1.获取前端表单上传的文件，获取文件名getOriginalFilename()，判断是否是Excel文件
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		// * 2.1不是Excel文件，直接返回提示信息
		if (!(fileName.contains("xls") || fileName.contains("xlsx"))) {
			// 格式错误
			model.addAttribute("error", "上传的文件格式不对");
			return "error";
		}
 
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		String realpath = request.getSession().getServletContext().getRealPath("/");
		System.out.println(realpath);
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		//String realpath = "D:/uploadExcel";
		File targetDir = new File(realpath+"/uploadExcel");
		if (!targetDir.exists()) {
			targetDir.mkdirs();
			System.out.println("不存在目录");
		}
		// * 4.将上传文件保存在上传目录中new File(realpath,fileName)
		File targetFile = new File(realpath+"/uploadExcel", fileName);
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			// 导入错误
			model.addAttribute("error", "文件上传失败");
			 return "error";
		}
		
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		// // 2: 解析excel数据
        List<String[]> excelData;
		try {
			excelData = POIUtil.readExcel(file,2);
		} catch (IOException e1) {
			model.addAttribute("error", e1.getMessage());
		     return "error";
		}

	     //批量插入
        try {
	        List<CountrySub> stuList = new ArrayList<CountrySub>();
	        for(String[] arr : excelData) {
	        	CountrySub stu = new CountrySub();
	        	stu.setNo(arr[0]);
	        	stu.setProject(arr[1].trim());
	        	stu.setSchoolname(arr[2].trim());
	        	stu.setTerm(arr[3].trim());
	        	//项目名 或学校名 任意一个为空  则不会继续导入
	        	if(stu.getProject()==null || stu.getSchoolname()==null) {
	        		break;
	        	}
	        	stu.setName(arr[4]);
	        	stu.setSex(arr[5]);
	        	stu.setGrade(arr[6]);
	        	stu.setClasses(arr[7]);
	        	stu.setIdcard(arr[8]);//身份证号
	        	if(arr[8]!=null && arr[8].trim().length()!=18) {
 	        		throw new Exception(arr[4].trim()+"的身份证号码必须18位");
 	        	}
	        	stu.setStucode(arr[9]);//学籍号
	        	stu.setType(arr[10]);//受助类别
	        	stu.setDescinfo(arr[11]);//详细原因
	        	stu.setProvince(arr[12]);//省
	        	stu.setCity(arr[13]);//市
	        	stu.setXian(arr[14]);//县
	        	stu.setTown(arr[15]);//镇
	        	stu.setCountry(arr[16]);//村
	        	stu.setCountrygroup(arr[17]);//组
	        	stu.setParentname(arr[18]);//家长姓名
	        	stu.setRelation(arr[19]);//关系
	        	stu.setPhone(arr[20]);//联系电话
	        	stu.setBankno(arr[21]);//银行卡号
	        	stu.setBankname(arr[22]);//银行名称
	        	stu.setAmount(new BigDecimal(arr[23]));//金额
	        	
//	        
//	        	stu.setName(arr[0].trim());
//	        	if(stu.getName()==null || "".equals(stu.getName())) {
//	        		break;  //如果学生姓名没有填，则不再往下读取
//	        	}
//	        	if(arr[1]!=null && arr[1].trim().length()!=18) {
//	        		throw new Exception(arr[0].trim()+"的身份证号码必须18位");
//	        	}
//	        	stu.setIdcard(arr[1].trim());// 身份证号   验证必须18位
//	        	stu.setStucode(arr[2].trim());//学籍号
//	        	stu.setTerm(arr[3].trim());//学期
//	        	stu.setLevel(arr[4].trim());//年级
//	        	stu.setClasses(arr[5].trim());//班级
//	        	stu.setIslodge(arr[6].trim());
//	        	stu.setSchoolName(arr[7].trim());
//	        	stu.setXueduan(arr[8].trim());
//	        	
	        	stu.setUid(user.getId());
	        	stu.setStatus(1);
	        	stuList.add(stu);
	        }
        	boolean flag  = service.insertBatch(stuList);
        	//成功
        	return "forward:/countrysub/list";
        }catch (Exception e) {
        	e.printStackTrace();
        	model.addAttribute("error", e.getMessage());
		     return "error";
		}finally {
			//删除服务器上的文件
			boolean flag=targetFile.delete();
			 System.out.println("===========删除标记："+flag);
		}
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteBatch")
	public String deleteBatch(String ids,Model model) {
		service.deleteBatch(ids);
		model.addAttribute("successFlag", "true");
		return "forward:/countrysub/list";
	}
}
